package com.ruike.alisurface.ui.mainPage;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.os.CountDownTimer;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.ruike.alisurface.Constant;
import com.ruike.alisurface.MyApplication;
import com.ruike.alisurface.R;
import com.ruike.alisurface.Serials.MsgEventBus;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.bean.CarGoodsBeans;
import com.ruike.alisurface.bean.GoodsBean;
import com.ruike.alisurface.bean.GoodsBeans;
import com.ruike.alisurface.bean.GoodsInfoBean;
import com.ruike.alisurface.http.MchApiHttp;
import com.ruike.alisurface.manager.HorizontalPageLayoutManager;
import com.ruike.alisurface.ui.adapter.GoodsCarTypeListAdapter;
import com.ruike.alisurface.ui.adapter.GoodsListTypeAdapter;
import com.ruike.alisurface.ui.dialog.GoodsInfoDialog;
import com.ruike.alisurface.utils.ShareKey;
import com.ruike.alisurface.utils.addCarAnimatorUtil;
import com.voodoo.lib_utils.ClickUtils;
import com.voodoo.lib_utils.GsonUtils;
import com.voodoo.lib_utils.L;
import com.voodoo.lib_utils.ScreenUtils;
import com.voodoo.lib_utils.ShareUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 测试按商品分类显示
 */
public class MainTypeActivity extends BaseAty {

    @BindView(R.id.main_goodsList_recv)
    RecyclerView mainGoodsListRecv;
    @BindView(R.id.main_left_imgv)
    ImageView mainLeftImgv;
    @BindView(R.id.main_right_imgv)
    ImageView mainRightImgv;
    @BindView(R.id.main_shopingCar_recv)
    RecyclerView mainShopingCarRecv;
    @BindView(R.id.main_goback_rlayout)
    RelativeLayout mainGobackRlayout;
    @BindView(R.id.main_buttonBar_llayout)
    LinearLayout mainButtonBarLlayout;
    @BindView(R.id.main_goAnswer_imgv)
    ImageView goAnswerImgv;
    @BindView(R.id.main_scrollbar_view)
    View mainScrollbarView;

    private List<GoodsBeans> goodsBeans = new ArrayList<>(); // 商品列表
    private List<GoodsBeans> goodsCarBeans = new ArrayList<>(); // 购物车的商品列表
    private GoodsListTypeAdapter goodsListAdapter; // 商品列表适配器
    private GoodsCarTypeListAdapter goodsCarListAdapter; // 商品购物车适配器
    private GoodsInfoDialog.Build goodsInfoDialogBuild;//商品详情页弹框信息
    private int position;// 商品详情页 商品索引值
    private List<CarGoodsBeans> goodsCarBeanss = new ArrayList<>(); // 的商品列表
    FrameLayout root_view;
    GridLayoutManager gridLayoutManager;
    boolean isOpenAdv;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_main;
    }

    @Override
    protected void onResume() {
        super.onResume();

        startCountdownTimer(120, null, VedioAdvActivity.class);

        goodsCarBeanss.clear();
        count = ShareUtils.getInstance().getInt(ShareKey.PURCHASE_COUNT);
        MyApplication.finalDbUtils.deleteAll(CarGoodsBeans.class);
    }

    @SuppressLint("ResourceAsColor")
    @Override
    protected void initViews() {
        isOpenAdv = ShareUtils.getInstance().getInt(ShareKey.ADV_TYPE, Constant.ADV_TYPE_NONE) == Constant.ADV_TYPE_NONE;
        initTitleBar(isOpenAdv);
        gridLayoutManager = new GridLayoutManager(this, 4); // 布局管理器所需参数，上下文
        gridLayoutManager.setReverseLayout(false); // 通过布局管理器，可以控制条目排列顺序  true：反向显示  false：正常显示(默认)
        gridLayoutManager.setOrientation(GridLayoutManager.HORIZONTAL); // 设置RecyclerView显示的方向，是水平还是垂直！！ GridLayoutManager.VERTICAL(默认) false
        mainGoodsListRecv.setLayoutManager(gridLayoutManager); // 设置布局管理器，参数 linearLayout
        mainGoodsListRecv.addOnScrollListener(new RecyclerView.OnScrollListener() { // 添加箭头滑动显隐监听
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                // 当前RecyclerView显示区域的高度，水平列表是从左到右的展示范围
                int extent = recyclerView.computeHorizontalScrollExtent();
                // 整体高度，包括显示在屏幕外的
                int range = recyclerView.computeHorizontalScrollRange();
                // 滚动过的距离，0表示处于顶部
                int offset = recyclerView.computeHorizontalScrollOffset();
                // 计算溢出的部分，及屏外剩下的宽度
                float maxEndX = range - extent;

                ViewGroup.LayoutParams layoutParams = mainScrollbarView.getLayoutParams();
                if (range <= extent) { // 整体高度 <= RecyclerView显示区域的高度

                    // 计算滑动条宽度填充整个屏幕
                    layoutParams.width = ScreenUtils.getScreenWidth(MainTypeActivity.this)[0];
                    mainScrollbarView.setLayoutParams(layoutParams);

                } else {
                    // 计算比例
                    double proportion = extent * 1.0 / range;

                    // 计算滑动条宽度并设置
                    layoutParams.width = (int) (proportion * extent);
                    mainScrollbarView.setLayoutParams(layoutParams);

                    // 滑块移动距离
                    mainScrollbarView.setTranslationX((int) (proportion * offset));
                }

                mainLeftImgv.setVisibility(offset <= 200 ? View.GONE : View.VISIBLE);
                mainRightImgv.setVisibility(offset >= maxEndX - 50 ? View.GONE : View.VISIBLE);
            }
        });

        HorizontalPageLayoutManager horizontalPageLayoutManager = new HorizontalPageLayoutManager(1, 3); // 设置行列
        mainShopingCarRecv.setLayoutManager(horizontalPageLayoutManager);
    }

    addCarAnimatorUtil animatorUtil;
    int count;


    @Override
    protected void initData() {
        showProgressDialog("加载数据中，请等待。。。");
        MchApiHttp.getSlotsType(this); // 获取商品列表数据
        root_view = findViewById(R.id.root_view);
        animatorUtil = new addCarAnimatorUtil();
        goodsListAdapter = new GoodsListTypeAdapter(this, goodsBeans);
        goodsListAdapter.setHasStableIds(true);
        ((DefaultItemAnimator) mainGoodsListRecv.getItemAnimator()).setSupportsChangeAnimations(false); // 取消动画效果

        goodsListAdapter.setOnGoodsItemClickListener(new GoodsListTypeAdapter.OnGoodsItemClickListener() {
            @Override
            public void onGoodsClick(int index, GoodsBeans clickBean) {
            }

            @Override
            public void onGoodsClick(ImageView imageView, int index, GoodsBeans clickBean) {
                if (clickBean.getCount() > 0 && goodsCarBeans.size() < ShareUtils.getInstance().getInt(ShareKey.PURCHASE_COUNT)) {
                    L.i("add_count==", count);
                    if (count <= 0) {
                        showErrorTip(new StringBuffer().append(getResources().getString(R.string.maxPurchaseQuantityStr)).
                                append(" ").append(ShareUtils.getInstance().getInt(ShareKey.PURCHASE_COUNT)).toString());
                        return;
                    } else {
                        count--;
                    }
                    animatorUtil.CarAnimationCanal();
                    addCar(index, clickBean);
                    animatorUtil.addGoodToCarAnimator(imageView, root_view, goAnswerImgv);
                    animatorUtil.setOnItemonAnimationEnd(new addCarAnimatorUtil.OnItemonAnimationEnd() {
                        @Override
                        public void onAnimationEnd() {
                            undataAdapter();
                        }
                    });

                } else if (clickBean.getCount() <= 0) {
                    showErrorTip(getResources().getString(R.string.goodsSoldOutStr));
                } else {
                    // 每次最多购买数量 3
                    showErrorTip(new StringBuffer().append(getResources().getString(R.string.maxPurchaseQuantityStr))
                            .append(" ").append(ShareUtils.getInstance().getInt(ShareKey.PURCHASE_COUNT)).toString());
                }
            }
        });
        goodsListAdapter.setOnItemGoodsInfoClickListener(new GoodsListTypeAdapter.OnItemGoodsInfoClickListener() {
            @Override
            public void onGoodsInfoClick(int index, GoodsBeans clickBean) {
                getGoodsinfo(index, clickBean);
            }
        });
        mainGoodsListRecv.setAdapter(goodsListAdapter);

        goodsCarListAdapter = new GoodsCarTypeListAdapter(this, goodsCarBeans);
        goodsCarListAdapter.setOnItemDeleteClickListener(new GoodsCarTypeListAdapter.OnItemDeleteClickListener() {
            @Override
            public void onGoodsDeleteClick(int index, GoodsBeans goodsBean) {
                List<GoodsBeans> list = new ArrayList<>();
                list.add(goodsBean);
                deleteCarGoods(list);
            }
        });
        mainShopingCarRecv.setAdapter(goodsCarListAdapter);
    }

    @OnClick({R.id.main_left_imgv, R.id.main_right_imgv})
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.main_goAnswer_imgv: // 去答题
                if (goodsCarBeans.size() > 0) {
                    for (GoodsBeans goodsBean : goodsCarBeans) {
                        CarGoodsBeans goodsBeans = new CarGoodsBeans();
                        goodsBeans.setCount(goodsBean.getCount());
                        goodsBeans.setPrice(goodsBean.getPrice());
                        goodsBeans.setProductid(goodsBean.getProductid());
                        goodsBeans.setProductimg(goodsBean.getProductimg());
                        goodsBeans.setProductname(goodsBean.getProductname());
                        String slotinde = GsonUtils.ListtoString(goodsBean.getSlotIndexs());
                        goodsBeans.setSlotIndexs(slotinde);
                        goodsCarBeanss.add(goodsBeans);
                    }
                    MyApplication.finalDbUtils.saveList(goodsCarBeanss);
//                    startActivity(AnswerConfirmActivity.class, null);
                    finish();
                } else {
                    showErrorTip(getResources().getString(R.string.pleaseChooseToBuyGoodsStr));
                }
                break;
            case R.id.main_left_imgv:
                // 平缓向右移动指定距离
                mainGoodsListRecv.smoothScrollBy(-810, 0);
                break;
            case R.id.main_right_imgv:
                // 平缓向左移动指定距离
                mainGoodsListRecv.smoothScrollBy(810, 0);
                break;
            default:
                break;
        }
    }

    /**
     * 添加到购物车
     *
     * @param index     点击的商品列表下标
     * @param clickBean 点击的对象
     */
    private void addCar(int index, GoodsBeans clickBean) {
        if (clickBean.getCount() > 0 && goodsCarBeans.size() < ShareUtils.getInstance().getInt(ShareKey.PURCHASE_COUNT)) {
            // 获取列表中的数据进行修改之后存入列表和修改数据表
            clickBean.setCount(clickBean.getCount() - 1);
            goodsBeans.set(index, clickBean);
            goodsListAdapter.setData(goodsBeans);
            // 数据表修改好之后添加到购物车数据表
            L.i("addCar", clickBean.toString());
            goodsCarBeans.add(clickBean);
        } else if (clickBean.getCount() <= 0) {
            showErrorTip(getResources().getString(R.string.goodsSoldOutStr));
        } else {
            // 每次最多购买数量 3
            showErrorTip(new StringBuffer().append(getResources().getString(R.string.maxPurchaseQuantityStr)).append(" ").append(ShareUtils.getInstance().getInt(ShareKey.PURCHASE_COUNT)).toString());
        }
    }

    public void undataAdapter() {
        goodsCarListAdapter.setData(goodsCarBeans);
    }

    /**
     * 删除购物车中的数据
     *
     * @param delGoodsBean 要删除的购物车数据对象
     */
    public void deleteCarGoods(List<GoodsBeans> delGoodsBean) {
        if (delGoodsBean == null) {
            return;
        }

        for (GoodsBeans goods : delGoodsBean) {
            Double Price = goods.getPrice();
            String Productid = goods.getProductid();
            for (int i = 0; i < goodsBeans.size(); i++) {
                GoodsBeans tempGoodsBean = goodsBeans.get(i);
                if (tempGoodsBean != null && tempGoodsBean.getProductid().equals(Productid)) {
                    if (tempGoodsBean != null && tempGoodsBean.getPrice() == Price) {
                        tempGoodsBean.setCount(tempGoodsBean.getCount() + 1);
                        goodsBeans.set(i, tempGoodsBean);

                        break;
                    }
                }
            }
        }

        if (delGoodsBean.size() > 1) { // 删除多个数据
            goodsCarBeans.clear();
            count = ShareUtils.getInstance().getInt(ShareKey.PURCHASE_COUNT);
        } else { // 删单个数据
            goodsCarBeans.remove(delGoodsBean.get(0));
            count++;
        }
        L.i("add_count=deleteCarGoods=", count);
        goodsListAdapter.setData(goodsBeans);
        goodsCarListAdapter.setData(goodsCarBeans);
    }

    @Override
    public void onSuccess(String requestUrl, String requestJsonStr) {
        super.onSuccess(requestUrl, requestJsonStr);
        try {
            JSONObject object = new JSONObject(requestJsonStr);
            String data = object.optString("data");

            if (requestUrl.endsWith("getProduct")) {  // 获取商品货道信息
                goodsBeans = GsonUtils.jsonArray2ModelList(data, GoodsBeans.class);
                if (goodsBeans == null) {
                    return;
                }
                goodsListAdapter.setData(goodsBeans);
                setXUdD();
                return;
            } else if (requestUrl.endsWith("Get_Productinfo")) {
                // 请求成功直接设置相应的属性值
                GoodsInfoBean goodsInfoBean = GsonUtils.json2Model(requestJsonStr, GoodsInfoBean.class);
                if (goodsInfoDialogBuild != null) {
                    goodsInfoDialogBuild.setInfoData(goodsInfoBean);
                } else {
                    showGoodsInfoDialog(position, goodsInfoBean);
                }
                return;
            }

        } catch (JSONException e) {
            L.i("onSuccess:JSON 字符串异常，一般不会在此出现该问题： " + e.toString());
            e.printStackTrace();
        }

    }

    Timer timer;
    Random ra = new Random();

    /**
     * 10秒 随机抖动
     */
    public void setXUdD() {
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            if (goodsBeans.size() > 0) {
                                int dd_count = (ra.nextInt(goodsBeans.size()));
                                goodsListAdapter.setDoudong(dd_count, mainGoodsListRecv);
                            }
                        } catch (Exception e) {
                            L.i("setXUdD====" + e.getMessage());
                        }
                    }
                });

            }
        }, 100, 10000);
    }

    @Override
    public void onFailure(String requestUrl, String requestMsg) {
        super.onFailure(requestUrl, requestMsg);
        L.i("Error====" + requestUrl + "====" + requestMsg);
        if (requestUrl.endsWith("Get_Productinfo")) {
            showErrorTip("信息获取失败，请检查网络...");
        }

    }

    // 展示商品详情界面弹窗
    public void getGoodsinfo(int position, GoodsBeans clickBean) {

        if (ClickUtils.isFastClick()) {
            this.position = position;
            // 1、展示弹窗
            showGoodsInfoDialog(position, null);

            MchApiHttp.getGoodsinfo(this, clickBean.getProductid()); // 获取商品列表数据

            // 3、创建一个倒计时
            new CountDownTimer(1000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                }

                @Override
                public void onFinish() {
                    // 倒计时结束直接取消请求

                    MchApiHttp.cancal("Get_Productinfo");
                }
            }.start();
        }
    }

    /**
     * 展示商品详情弹窗界面
     *
     * @param position 点击商品的下标索引
     */
    private void showGoodsInfoDialog(final int position, GoodsInfoBean goodsInfoBean) {

        View activityView = getWindow().getDecorView();
        activityView.setDrawingCacheEnabled(true);
        activityView.destroyDrawingCache();
        activityView.buildDrawingCache();
        Bitmap bmp = activityView.getDrawingCache();


        if (GoodsInfoDialog.dialog != null && GoodsInfoDialog.dialog.isShowing()) { // 展示详情弹窗
            GoodsInfoDialog.dialog.dismiss();
        }
        GoodsBean goodsBean = new GoodsBean();
        goodsBean.setCount(goodsBeans.get(position).getCount());
        goodsBean.setPrice(goodsBeans.get(position).getPrice());
        goodsBean.setProductimg(goodsBeans.get(position).getProductimg());
        goodsBean.setProductid(goodsBeans.get(position).getProductid());
//        goodsBean.setIndex(goodsBeans.get(position).getSlotIndexs().get(0));
        goodsInfoDialogBuild = new GoodsInfoDialog.Build(this)
                .setPosition(position)
                .setGoodsBean(goodsBean)
                .setBackground(bmp);
        goodsInfoDialogBuild.setOnDialogClickListener(new GoodsInfoDialog.Build.OnDialogClickListener() {
            @Override
            public void onDialogClose() {
            }

            @Override
            public void onAddCar(int position) {
                addCar(position, goodsBeans.get(position));
                undataAdapter();
            }
        });
        goodsInfoDialogBuild.show();
        goodsInfoDialogBuild.setInfoData(goodsInfoBean);

    }


    @Override
    public void onError(String requestUrl, String errorMsg) {
        super.onError(requestUrl, errorMsg);


    }

    @Override
    public void doEventBusResult(MsgEventBus event) {

    }

    @Override
    protected void onStop() {
        super.onStop();
        if (timer != null) {
            L.i("onStop====");
            timer.cancel();
            timer = null;
        }
        if (animatorUtil != null) {
            animatorUtil.CarAnimationCanal();
        }

        if (GoodsInfoDialog.dialog != null && GoodsInfoDialog.dialog.isShowing()) { // 展示详情弹窗
            GoodsInfoDialog.dialog.dismiss();
            GoodsInfoDialog.dialog = null;
        }
    }
}
